//
//  ForgetPassworldViewController.m
//  Application
//
//  Created by 薛小刚 on 2017/12/21.
//  Copyright © 2017年 薛小刚. All rights reserved.
//

#import "ForgetPassworldViewController.h"
#import "NSString+DES.h"
#import <UMPush/UMessage.h>
#import "B_PerfectUserMessageVC.h"

@interface ForgetPassworldViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
/// 关闭按钮
- (IBAction)closeButtonClicked:(id)sender;
/// 验证码的view
@property (weak, nonatomic) IBOutlet UIView *codeView;
/// 验证码输入框
@property (weak, nonatomic) IBOutlet UITextField *codeInputView;
/// 获取验证码的按钮
@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;
/// 获取验证码的点击事件
- (IBAction)getCodeButtonClicked:(id)sender;
/// 密码的view
@property (weak, nonatomic) IBOutlet UIView *passWorldView;
/// 密码的数据框
@property (weak, nonatomic) IBOutlet UITextField *passWorldInputView;
/// 登录按钮点击事件
- (IBAction)loginButtonClicked:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@end

@implementation ForgetPassworldViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    isAnimation = NO;
    self.passWorldInputView.delegate = self;
    [self setUI];
    [self getImage];
    [self.view sendSubviewToBack:self.backgroundImageView];
}
- (void)getImage {
    [NetworkingManager getNetworkRequestWithUrlString:@"http://39.106.113.252/bgmimg.json" parameters:nil isCache:NO succeed:^(id data) {
        [self.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:data[@"img"]]];
    } fail:^(NSError *error) {
        self.backgroundImageView.backgroundColor = [UIColor blackColor];
    }];
}


static bool isAnimation;
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:isAnimation];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

/**
 设置UI
 */
- (void) setUI {
    
    [self.codeInputView setValue:UIColorFromRGB(0xafafaf) forKeyPath:@"_placeholderLabel.textColor"];
    [self.passWorldInputView setValue:UIColorFromRGB(0xafafaf) forKeyPath:@"_placeholderLabel.textColor"];
//    self.passWorldView.layer.masksToBounds      = YES;
//    self.passWorldView.layer.cornerRadius       = 4;
//    self.passWorldView.layer.borderColor        = xgLineColor.CGColor;
//    self.passWorldView.layer.borderWidth        = 1;
//
//    self.getCodeButton.layer.masksToBounds      = YES;
//    self.getCodeButton.layer.cornerRadius       = 4;
//    self.getCodeButton.layer.borderColor        = xgRedColor.CGColor;
//    self.getCodeButton.layer.borderWidth        = 1;
//
//    self.codeView.layer.masksToBounds           = YES;
//    self.codeView.layer.cornerRadius            = 4;
//    self.codeView.layer.borderColor             = xgLineColor.CGColor;
//    self.codeView.layer.borderWidth             = 1;
    
//    [self.loginButton setTitleColor:xgTextGlodColor forState:UIControlStateNormal];
//    self.loginButton.backgroundColor = xgBackBlackColor;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (IBAction)closeButtonClicked:(id)sender {
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)getCodeButtonClicked:(id)sender {
    [self.view endEditing:YES];
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/login/mobelSendMessage" parameters:@{@"str": [NSString getEncypt:@{@"LiZhenyangMobilePhone": getMobile(), @"LiZhenyangCode":@"178180"}]} isCache:NO succeed:^(id data) {
        if ([data[@"code"] intValue] == 10015) {
            [KeyWindow makeToast:@"验证码获取成功,请注意查收!"];
            [self timeFire];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}
- (IBAction)loginButtonClicked:(id)sender {
    [self.view endEditing:YES];
    if (ISNULL(self.codeInputView.text)) {
        [UIView xg_toast:@"请输入验证码"];
        return;
    }
    if (ISNULL(self.passWorldInputView.text)) {
        [UIView xg_toast:@"请输入密码"];
        return;
    }
    if (self.passWorldInputView.text.length < 6) {
        [KeyWindow makeToast:@"密码不能少于6位"];
        return;
    }
    
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/login/editPassword" parameters:@{@"str": [NSString getEncypt:@{@"XxwyzValidateCode":self.codeInputView.text, @"XxwyzMobile":getMobile(),                                                                                                                         @"XxwyzPassword" : [self.passWorldInputView.text MD5], @"XxwyzCode":@"158178"}]} isCache:NO succeed:^(id data) {
        if ([data[@"code"] intValue] == 10025) {
            
            /// 调用登录接口
            [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/login/login" parameters:@{@"str": [NSString getEncypt:@{@"XxwyzMobile" : getMobile(), @"XxwyzPassword" : [self.passWorldInputView.text MD5], @"XxwyzdeviceNumber" : getDeviceNumber(), @"XxwyzCode" : @"158178", @"XxwyzType" : @"2"}]} isCache:NO succeed:^(id data) {
                if ([data[@"code"] intValue] == 10000) {
                    
                    setUserId([NSString stringWithFormat:@"%@", data[@"values"][@"id"]]);
                    setToken([NSString stringWithFormat:@"%@", data[@"values"][@"token"]]);
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshUserMessage" object:nil];
                    [UMessage addAlias:[NSString stringWithFormat:@"%@", data[@"values"][@"id"]] type:kUMessageAliasTypeQQ response:^(id responseObject, NSError *error) {
                        HXLog(@"失败信息是      %@", error);
                    }];
                    
                    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/login/userIsFillInfo/%@", getUserId()] parameters:nil isCache:NO succeed:^(id data) {
                        if ([data[@"code"] isEqualToString:@"2"]) {     // 信息不完善 完善信息
                            B_PerfectUserMessageVC * vc = [[B_PerfectUserMessageVC alloc] init];
                            
                            [self pushNextViewController:vc];
                        } else {
                            [self.navigationController.viewControllers.firstObject dismissViewControllerAnimated:YES completion:nil];
                        }
                    } fail:^(NSError *error) {
                        [KeyWindow makeToast:@"服务器异常"];
                    }];
                    
                    //            [self.navigationController.viewControllers.firstObject dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [KeyWindow makeToast:data[@"message"]];
                }
                
            } fail:^(NSError *error) {
                
            }];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}



/**
 倒计时
 */
- (void) timeFire {
    //验证码获取时间倒计时
    __block int timeout = 59; //倒计时时间
    //优先级
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 （倒计时结束后调用）
                [_getCodeButton setTitle:@"验证码" forState:UIControlStateNormal];
                //设置不可点击
                _getCodeButton.userInteractionEnabled = YES;
                //                _getCodeBtn.backgroundColor = [UIColor clearColor];
                
            });
        }else{
            //
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [_getCodeButton setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                //设置不可点击
                _getCodeButton.userInteractionEnabled = NO;
                //                _getCodeBtn.backgroundColor = [UIColor clearColor];
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
    
}

#pragma mark -> 输入框的代理方法

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    HXLog(@"%@", textField.text);
    if (textField.text.length > 15) {
        return NO;
    }
    return YES;
}

- (void)dealloc {
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [[SDImageCache sharedImageCache] clearMemory];
}

@end
